import copy
from datetime import datetime
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter.messagebox import showinfo, showwarning
from pymysql import connect
import numpy as np
import random


class GameView:
    def __init__(self):
        self.conn = connect(host="localhost", port=3306, user="root", password="123456", database="xhm")
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()
        self.log_name = None
        self.log_pwd = None
        self.root = None
        self.root1 = None
        self.root2 = None
        self.log_name1 = None
        self.log_pwd1 = None
        self.log_confirm_psw = None
        self.map_combobox = None
        self.difficulty_combobox = None
        self.rank_type_combobox = None
        self.text = None

    def first_view(self):
        self.root = Tk()
        self.root.title('登录页面')
        self.root.geometry("800x400+100+150")
        self.log_name = StringVar()
        self.log_pwd = StringVar()
        Label(self.root, text='用户名:', font=('幼圆', 20)).place(x=170, y=80)
        Entry(width=27, font=('幼圆', 20), textvariable=self.log_name).place(x=280, y=88)
        Label(self.root, text='密码:', font=('幼圆', 20)).place(x=200, y=150)
        Entry(width=27, font=('幼圆', 20), show='*', textvariable=self.log_pwd).place(x=280, y=150)

        Button(text='登录',
               background='white',  # 背景色
               foreground='black', width=15,  # 前景色
               font=('幼圆', 20),  # 字体  大小
               command=self.admin_login).place(x=50, y=250)
        Button(text='注册',
               background='white',  # 背景色
               foreground='black',  # 前景色
               width=15, font=('幼圆', 20),  # 字体  大小
               command=lambda: self.register()).place(x=300, y=250)
        Button(text='退出',
               background='white',  # 背景色
               foreground='black',  # 前景色
               width=15, font=('幼圆', 20),  # 字体  大小
               command=lambda: self.root.quit()).place(x=550, y=250)
        self.root.mainloop()

    def admin_login(self):
        username = self.log_name.get()
        userpsw = self.log_pwd.get()
        player = "SELECT player_name,psw FROM player WHERE player_name=%s AND psw=%s"
        self.cursor.execute(player, (username, userpsw))
        result = self.cursor.fetchone()

        if result:
            admin_name = result[0]
            showinfo('提示信息', f'玩家 {admin_name} 登录成功!')
            self.log_name = admin_name
            self.root.withdraw()  # 隐藏登录页面
            self.home_page()
        else:
            showwarning('提示信息', '用户名或密码输入有误!')

    def register(self):
        self.root.destroy()
        self.root1 = Tk()
        self.root1.title('注册')
        self.root1.geometry("800x400+200+200")
        self.log_name1 = StringVar()
        self.log_pwd1 = StringVar()
        self.log_confirm_psw = StringVar()
        Label(self.root1, text='用户名:', font=('幼圆', 20)).place(x=170, y=80)
        Entry(width=27, font=('幼圆', 20), textvariable=self.log_name1).place(x=280, y=88)

        Label(self.root1, text='密码:', font=('幼圆', 20)).place(x=200, y=150)
        Entry(width=27, font=('幼圆', 20), show='*', textvariable=self.log_pwd1).place(x=280, y=150)

        Label(self.root1, text='确认密码:', font=('幼圆', 20)).place(x=150, y=210)
        Entry(width=27, font=('幼圆', 20), show='*', textvariable=self.log_confirm_psw).place(x=280, y=212)

        Button(text='注册用户',
               background='white',  # 背景色
               foreground='black',  # 前景色
               width=15, font=('幼圆', 20),  # 字体  大小
               command=lambda: self.add_player()).place(x=300, y=300)
        self.root1.mainloop()

    def add_player(self):
        play_name = self.log_name1.get()
        play_psw = self.log_pwd1.get()
        play_confirm_psw = self.log_confirm_psw.get()
        if play_psw == play_confirm_psw:
            sql = "insert into player(player_name,psw) values (%s,%s)"
            val = (play_name, play_psw)
            self.cursor.execute(sql, val)
            self.conn.commit()
            showinfo('提示信息', f'注册成功!')
        else:
            showwarning('提示信息', '注册失败!')

    def home_page(self):
        root = tk.Tk()
        root.title('关灯游戏')
        root.geometry('500x300+500+200')
        min = Min()
        min.name = self.log_name
        medium = Medium()
        medium.name = self.log_name
        max = Max()
        max.name = self.log_name
        tk.Label(root, text='关灯游戏', font=('微软雅黑', 20)).grid(row=0, column=0, columnspan=10, pady=20)
        button1 = tk.Button(root, text='小地图', font=('微软雅黑', 15), bg='grey', width=10, relief="flat",
                            command=min.min_map)
        button2 = tk.Button(root, text='中地图', font=('微软雅黑', 15), bg='grey', width=10, relief="flat",
                            command=medium.medium_map)
        button3 = tk.Button(root, text='大地图', font=('微软雅黑', 15), bg='grey', width=10, relief="flat",
                            command=max.max_map)
        button4 = tk.Button(root, text='排行榜', font=('微软雅黑', 15), bg='grey', width=10, relief="flat",
                            command=self.ranking_view)
        button1.grid(row=1, column=0, columnspan=10, pady=(0, 10))
        button2.grid(row=2, column=0, columnspan=10, pady=(0, 10))
        button3.grid(row=3, column=0, columnspan=10, pady=(0, 10))
        button4.grid(row=4, column=0, columnspan=10, pady=(0, 10))
        # 设置列权重，使其居中对齐
        root.columnconfigure(0, weight=1)
        # 设置行权重，使其居中对齐
        root.rowconfigure(1, weight=1)
        root.rowconfigure(2, weight=1)
        root.rowconfigure(3, weight=1)
        root.rowconfigure(4, weight=1)
        root.mainloop()

    def ranking_view(self):
        self.root2 = tk.Tk()
        self.root2.title("通关排行榜")
        self.root2.geometry("800x550+200+100")
        map_label = tk.Label(self.root2, text="地图大小:", font=('微软雅黑', 15))
        map_label.place(x=10, y=10)
        map_combobox = ttk.Combobox(self.root2, values=["小地图", "中地图", "大地图"], font=('微软雅黑', 15))
        map_combobox.current(0)
        map_combobox.place(x=110, y=10)
        difficulty_label = tk.Label(self.root2, text="难度：", font=('微软雅黑', 15))
        difficulty_label.place(x=10, y=60)
        difficulty_combobox = ttk.Combobox(self.root2, values=["容易", "中等", "困难"], font=('微软雅黑', 15))
        difficulty_combobox.current(0)
        difficulty_combobox.place(x=70, y=60)
        rank_type_label = tk.Label(self.root2, text="排名类型：", font=('微软雅黑', 15))
        rank_type_label.place(x=10, y=110)
        rank_type_combobox = ttk.Combobox(self.root2, values=["通关时间", "点击次数"], font=('微软雅黑', 15))
        rank_type_combobox.current(0)
        rank_type_combobox.place(x=110, y=110)
        ranking_label = tk.Label(self.root2, text="排行榜类型:", font=('微软雅黑', 15))
        ranking_label.place(x=10, y=160)
        ranking_combobox = ttk.Combobox(self.root2, values=["个人排名", "全国排名"], font=('微软雅黑', 15))
        ranking_combobox.current(0)
        ranking_combobox.place(x=130, y=160)
        tk.Button(self.root2, text="显示排行榜", font=('微软雅黑', 15),
                  command=lambda: self.ranking(map_combobox, difficulty_combobox, rank_type_combobox,
                                               ranking_combobox)).place(x=10, y=210)
        self.text = tk.Text(self.root2, width=70, height=40)
        self.text.place(x=10, y=260)
        self.root2.mainloop()

    def ranking(self, map_combobox, difficulty_combobox, rank_type_combobox, ranking_combobox):
        map_type = map_combobox.get()
        difficulty = difficulty_combobox.get()
        rank_type = rank_type_combobox.get()
        ranking_type = ranking_combobox.get()
        print(type(map_type))
        if rank_type == "点击次数":
            if ranking_type == "个人排名":
                sql = ("SELECT player_name, click_count FROM game_time WHERE map_type = %s AND difficulty = %s "
                       "AND player_name = %s ORDER BY click_count DESC ")
            else:
                sql = ("SELECT player_name, click_count FROM game_time WHERE map_type = %s AND difficulty = %s "
                       "ORDER BY click_count DESC ")
        else:
            if ranking_type == "个人排名":
                sql = ("SELECT player_name, through_time FROM game_time WHERE map_type = %s AND difficulty = %s "
                       "AND player_name = %s ORDER BY through_time ASC")
            else:
                sql = ("SELECT player_name, through_time FROM game_time WHERE map_type = %s AND difficulty = %s "
                       "ORDER BY through_time ASC")

        if ranking_type == "个人排名":
            player_name = self.log_name
            self.cursor.execute(sql, (map_type, difficulty, player_name))
        else:
            self.cursor.execute(sql, (map_type, difficulty))
        results = self.cursor.fetchall()  # 获取执行 SQL 查询后的所有结果

        self.text.delete("1.0", tk.END)  # 清空text
        self.text.insert(tk.END, "\t\t\t\t排行榜\n\n")

        for i, result in enumerate(results):
            player = result[0]
            score = result[1]
            self.text.insert(tk.END,
                             f"{i + 1}\t\t{player}\t\t{'点击次数' if rank_type == '点击次数' else '通关时间'}: {score}\n")


class Min:
    def __init__(self):
        self.ones_indices = []
        self.l = []
        self.num_lit = int(25 * 0.2)
        self.root = None
        self.cv = None
        self.start_time = None
        self.end_time = None
        self.click_count = 0
        self.conn = connect(host="localhost", port=3306, user="root", password="123456", database="xhm")
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()
        self.difficulty = None
        self.testfu = None
        self.name = None

    def set_light_percentage(self, percentage):
        self.num_lit = int(16 * (1-percentage))  # 根据选择的百分比计算亮灯的数量
        if percentage == 0.2:
            self.difficulty = "容易"
        elif percentage == 0.4:
            self.difficulty = "中等"
        elif percentage == 0.6:
            self.difficulty = "困难"
        else:
            print("发生错误！")

    def start_game(self):

        self.start_time = datetime.now()
        self.l = np.zeros((5, 5))
        print(f"test", self.l)
        self.l = Matrix(self.l, self.num_lit)

        # print(f"当前游戏矩阵", self.l)
        # self.l = Matrix(self.l)

        # 随机生成亮灯的格子
        # lattice = random.sample(range(25), self.num_lit)  # 随机选择亮灯格子的索引
        # for index in lattice:
        #     x = index // 5
        #     y = index % 5
        #     self.l[x][y] = 1

        self.huaqi()

    def huaqi(self):
        # 绘制灯的状态情况图
        for i in range(0, 5):
            for u in range(0, 5):
                if self.l[i][u] == 1:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='yellow', width=2)  # 亮灯
                else:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='white', width=2)  # 灭灯

    def min_map(self):
        self.root = Tk()
        self.root.title("选择亮灯比例")
        frame = Frame(self.root)
        Button(frame, text="开始游戏", command=self.start_game).pack()
        Button(frame, text="容易", command=lambda: self.set_light_percentage(0.2)).pack(side=LEFT)
        Button(frame, text="中等", command=lambda: self.set_light_percentage(0.4)).pack(side=LEFT)
        Button(frame, text="困难", command=lambda: self.set_light_percentage(0.6)).pack(side=LEFT)
        frame.pack(anchor=N)
        self.cv = Canvas(self.root, bg='white', width=210, height=210)
        for i in range(0, 6):
            self.cv.create_line(10, 10 + i * 40, 210, 10 + i * 40)
            self.cv.create_line(10 + i * 40, 10, 10 + i * 40, 210)
        self.cv.bind('<Button-1>', self.luozi)
        self.cv.pack()
        self.root.mainloop()

    def luozi(self, event):
        self.click_count += 1
        x1 = (event.x - 10) // 40
        y1 = (event.y - 10) // 40
        print(x1, y1)
        self.ones_indices.append((x1, y1))
        k=find_ones_indices(self.l)
        ols=find_union(k,self.ones_indices)
        print(f"小助手最优解",ols)
        self.reserve(x1, y1)  # 翻转(x1,y1)处灯的状态
        # 以下翻转(x1,y1)周围的灯的状态
        # 左侧灯的状态反转
        if x1 != 0:
            self.reserve(x1 - 1, y1)
        # 右侧灯的状态反转
        if x1 != 4:
            self.reserve(x1 + 1, y1)
        # 上侧灯的状态反转
        if y1 != 0:
            self.reserve(x1, y1 - 1)
        # 下侧灯的状态反转
        if y1 != 4:
            self.reserve(x1, y1 + 1)
        self.huaqi()
        p = sum(1 for i in range(0, 5) for u in self.l[i] if u == 0)
        if p == 25:
            self.end_time = datetime.now()
            self.get_through_time(self.click_count)
            messagebox.showinfo('win', '你过关了')

    def reserve(self, x1, y1):
        if self.l[x1][y1] == 0:
            self.l[x1][y1] = 1
        else:
            self.l[x1][y1] = 0

    def get_through_time(self, click_count):
        through_time = self.end_time - self.start_time
        print("通关时长：", through_time)
        print("点击次数：", click_count)
        sql = ("insert into game_time (map_type,player_name,through_time,end_time,click_count,difficulty) values (%s,"
               "%s,%s,%s,%s,%s)")
        player = self.name
        # game.log_name
        gameview = "小地图"
        val = (gameview, player, through_time, self.end_time, str(click_count), self.difficulty)
        self.cursor.execute(sql, val)
        self.conn.commit()
        print("录入数据库成功！")


class Medium:
    def __init__(self):
        self.l = []
        self.num_lit = int(64 * 0.2)
        self.root = None
        self.cv = None
        self.start_time = None
        self.end_time = None
        self.click_count = 0
        self.conn = connect(host="localhost", port=3306, user="root", password="123456", database="xhm")
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()
        self.difficulty = None
        self.name = None

    def set_light_percentage(self, percentage):
        self.num_lit = int(49 * (1 - percentage))  # 根据选择的百分比计算亮灯的数量
        if percentage == 0.2:
            self.difficulty = "容易"
        elif percentage == 0.4:
            self.difficulty = "中等"
        elif percentage == 0.6:
            self.difficulty = "困难"
        else:
            print("发生错误！")

    def start_game(self):
        self.start_time = datetime.now()
        self.start_time = datetime.now()
        self.l = np.zeros((8, 8))
        print(f"test", self.l)
        self.l = Matrix(self.l, self.num_lit)
        # 随机生成亮灯的格子
        # lattice = random.sample(range(64), self.num_lit)  # 随机选择亮灯格子的索引
        # for index in lattice:
        #     x = index // 8
        #     y = index % 8
        #     self.l[x][y] = 'you'
        self.huaqi()

    def huaqi(self):
        # 绘制灯的状态情况图
        for i in range(0, 8):
            for u in range(0, 8):
                if self.l[i][u] == 1:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='yellow', width=2)  # 亮灯
                else:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='white', width=2)  # 灭灯

    def medium_map(self):
        self.root = Tk()
        self.root.title("选择亮灯比例")
        frame = Frame(self.root)
        Button(frame, text="开始游戏", command=self.start_game).pack()
        Button(frame, text="容易", command=lambda: self.set_light_percentage(0.2)).pack(side=LEFT)
        Button(frame, text="中等", command=lambda: self.set_light_percentage(0.4)).pack(side=LEFT)
        Button(frame, text="困难", command=lambda: self.set_light_percentage(0.6)).pack(side=LEFT)
        frame.pack(anchor=N)
        self.cv = Canvas(self.root, bg='white', width=336, height=336)
        for i in range(0, 9):
            self.cv.create_line(10, 10 + i * 40, 336, 10 + i * 40)
            self.cv.create_line(10 + i * 40, 10, 10 + i * 40, 336)
        self.cv.bind('<Button-1>', self.luozi)
        self.cv.pack()
        self.root.mainloop()

    def luozi(self, event):
        self.click_count += 1
        x1 = (event.x - 10) // 40
        y1 = (event.y - 10) // 40
        print(x1, y1)
        self.reserve(x1, y1)  # 翻转(x1,y1)处灯的状态
        # 以下翻转(x1,y1)周围的灯的状态
        # 左侧灯的状态反转
        if x1 != 0:
            self.reserve(x1 - 1, y1)
        # 右侧灯的状态反转
        if x1 != 7:
            self.reserve(x1 + 1, y1)
        # 上侧灯的状态反转
        if y1 != 0:
            self.reserve(x1, y1 - 1)
        # 下侧灯的状态反转
        if y1 != 7:
            self.reserve(x1, y1 + 1)
        self.huaqi()
        p = sum(1 for i in range(0, 8) for u in self.l[i] if u == 0)
        if p == 64:
            self.end_time = datetime.now()
            self.get_through_time(self.click_count)
            messagebox.showinfo('win', '你过关了')

    def reserve(self, x1, y1):
        if self.l[x1][y1] == 0:
            self.l[x1][y1] = 1
        else:
            self.l[x1][y1] = 0

    def get_through_time(self, click_count):
        through_time = self.end_time - self.start_time
        print("通关时长：", through_time)
        print("点击次数：", click_count)
        sql = ("insert into game_time (map_type,player_name,through_time,end_time,click_count,difficulty) values (%s,"
               "%s,%s,%s,%s,%s)")
        player = self.name
        gameview = "中地图"
        val = (gameview, player, through_time, self.end_time, str(click_count), self.difficulty)
        self.cursor.execute(sql, val)
        self.conn.commit()
        print("录入数据库成功！")


class Max:
    def __init__(self):
        self.l = []
        self.num_lit = int(120 * 0.2)
        self.root = None
        self.cv = None
        self.start_time = None
        self.end_time = None
        self.click_count = 0
        self.conn = connect(host="localhost", port=3306, user="root", password="123456", database="xhm")
        # 使用 cursor() 方法创建一个游标对象 cursor
        self.cursor = self.conn.cursor()
        self.difficulty = None
        self.name = None

    def set_light_percentage(self, percentage):
        self.num_lit = int(99 *(1- percentage))  # 根据选择的百分比计算亮灯的数量
        if percentage == 0.2:
            self.difficulty = "容易"
        elif percentage == 0.4:
            self.difficulty = "中等"
        elif percentage == 0.6:
            self.difficulty = "困难"
        else:
            print("发生错误！")

    def start_game(self):
        self.start_time = datetime.now()
        self.start_time = datetime.now()
        self.l = np.zeros((12, 10))
        print(f"test", self.l)
        self.l = Matrix(self.l, self.num_lit)

        # 随机生成亮灯的格子
        # lattice = random.sample(range(120), self.num_lit)  # 随机选择亮灯格子的索引
        # for index in lattice:
        #     x = index // 10
        #     y = index % 10
        #     self.l[x][y] = 'you'
        self.huaqi()

    def huaqi(self):
        # 绘制灯的状态情况图
        for i in range(0, 12):
            for u in range(0, 10):
                if self.l[i][u] == 1:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='yellow', width=2)  # 亮灯
                else:
                    self.cv.create_oval(i * 40 + 10, u * 40 + 10, (i + 1) * 40 + 10, (u + 1) * 40 + 10, outline='white',
                                        fill='white', width=2)  # 灭灯

    def max_map(self):
        self.root = Tk()
        self.root.title("选择亮灯比例")
        frame = Frame(self.root)
        Button(frame, text="开始游戏", command=self.start_game).pack()
        Button(frame, text="容易", command=lambda: self.set_light_percentage(0.2)).pack(side=LEFT)
        Button(frame, text="中等", command=lambda: self.set_light_percentage(0.4)).pack(side=LEFT)
        Button(frame, text="困难", command=lambda: self.set_light_percentage(0.6)).pack(side=LEFT)
        frame.pack(anchor=N)
        self.cv = Canvas(self.root, bg='white', width=504, height=420)
        for i in range(0, 11):
            self.cv.create_line(10, 10 + i * 40, 504, 10 + i * 40)
        for i in range(0, 13):
            self.cv.create_line(10 + i * 40, 10, 10 + i * 40, 420)
        self.cv.bind('<Button-1>', self.luozi)
        self.cv.pack()
        self.root.mainloop()

    def luozi(self, event):
        self.click_count += 1
        x1 = (event.x - 10) // 40
        y1 = (event.y - 10) // 40
        print(x1, y1)
        self.reserve(x1, y1)  # 翻转(x1,y1)处灯的状态
        # 以下翻转(x1,y1)周围的灯的状态
        # 左侧灯的状态反转
        if x1 != 0:
            self.reserve(x1 - 1, y1)
        # 右侧灯的状态反转
        if x1 != 11:
            self.reserve(x1 + 1, y1)
        # 上侧灯的状态反转
        if y1 != 0:
            self.reserve(x1, y1 - 1)
        # 下侧灯的状态反转
        if y1 != 9:
            self.reserve(x1, y1 + 1)
        self.huaqi()
        p = sum(1 for i in range(0, 12) for u in self.l[i] if u == 0)
        if p == 120:
            self.end_time = datetime.now()
            self.get_through_time(self.click_count)
            messagebox.showinfo('win', '你过关了')

    def reserve(self, x1, y1):
        if self.l[x1][y1] == 0:
            self.l[x1][y1] = 1
        else:
            self.l[x1][y1] = 0

    def get_through_time(self, click_count):
        through_time = self.end_time - self.start_time
        print("通关时长：", through_time)
        print("点击次数：", click_count)
        sql = ("insert into game_time (map_type,player_name,through_time,end_time,click_count,difficulty) values (%s,"
               "%s,%s,%s,%s,%s)")
        player = self.name
        gameview = "大地图"
        val = (gameview, player, through_time, self.end_time, str(click_count), self.difficulty)
        self.cursor.execute(sql, val)
        self.conn.commit()
        print("录入数据库成功！")


def Matrix(matrix, pact):
    rows = len(matrix)
    cols = len(matrix[0])
    n = cols * cols
    m = rows * rows
    zero_matrix = np.zeros((n, m))

    for i in range(len(zero_matrix)):
        zero_matrix[i][i] = 1
        # 检查上方
        if i - cols >= 0:
            zero_matrix[i][i - cols] = 1
        # 检查下方
        if i + cols < n:
            zero_matrix[i][i + cols] = 1
        # 检查左侧
        if i % cols - 1 >= 0:
            zero_matrix[i][i - 1] = 1
        # 检查右侧
        if i % cols + 1 < cols:
            zero_matrix[i][i + 1] = 1
    # print(zero_matrix)
    zero_matrix = xor_inverse(zero_matrix, pact)
    print(zero_matrix)

    for j in range(rows):
        for k in range(cols):
            matrix[j][k] = np.bitwise_xor.reduce(zero_matrix[j + k, :].astype(int))
    matrix = matrix.astype(int)
    print(matrix)
    l = matrix_show(matrix)
    return l


def xor_inverse(matrix, k):
    rank = np.linalg.matrix_rank(matrix)
    y = np.eye(len(matrix))
    # print(f"当前矩阵主对角线情况", y)
    set_random_diagonal_elements(y, k, 0)
    # print(f"覆盖率为20%时主对角线情况", y)

    # for l in range(5):
    #     y[l][l]=0
    # print("满足60% ")
    # print(y)

    # print("矩阵的秩为:", rank)
    n = len(matrix)
    augmented_matrix = np.hstack((matrix, y))
    # np.savetxt('augmented_matrix.txt', augmented_matrix)

    # print(augmented_matrix)

    for i in range(n):
        pivot_row = np.argmax(augmented_matrix[i:, i]) + i
        augmented_matrix[[i, pivot_row]] = augmented_matrix[[pivot_row, i]]

        diagonal_element = augmented_matrix[i, i]

        # Check if diagonal_element is zero before dividing
        if diagonal_element != 0:
            augmented_matrix[i, :] = augmented_matrix[i, :] / diagonal_element
        else:
            # Handle division by zero, for example, swap rows or skip division
            pass

        for j in range(n):
            if i != j and augmented_matrix[j, i] == 1:
                augmented_matrix[j, :] = np.logical_xor(augmented_matrix[j, :], augmented_matrix[i, :])

    inverse = augmented_matrix[:, n:]

    # Handle invalid values (NaN or inf) in the inverse matrix
    inverse[np.isnan(inverse)] = 0
    inverse[np.isinf(inverse)] = 0

    return inverse.astype(int)


def matrix_show(matrix):
    # Calculate the number of rows and columns manually for a list of lists
    rows = len(matrix)
    cols = len(matrix[0]) if rows > 0 else 0

    deep_copy = copy.deepcopy(matrix)

    # Iterate through each element in the matrix
    for i in range(rows):
        for j in range(cols):
            if matrix[i][j] == 1:
                # Fill above
                if i - 1 >= 0:
                    deep_copy[i - 1][j] = 1 ^ deep_copy[i - 1][j]
                # Fill below
                if i + 1 < rows:
                    deep_copy[i + 1][j] = 1 ^ deep_copy[i + 1][j]
                # Fill left
                if j - 1 >= 0:
                    deep_copy[i][j - 1] = 1 ^ deep_copy[i][j - 1]
                # Fill right
                if j + 1 < cols:
                    deep_copy[i][j + 1] = 1 ^ deep_copy[i][j + 1]

    print(f"当前亮灯的矩阵: {deep_copy}")
    return deep_copy


def set_random_diagonal_elements(matrix, k, value):
    # 获取矩阵的行数和列数
    rows, cols = matrix.shape

    # 主对角线上的元素个数
    diagonal_size = min(rows, cols)

    # 确保 k 不超过主对角线上的元素个数
    k = min(k, diagonal_size)

    # 生成包含主对角线上所有元素下标的一维数组
    diagonal_indices = np.arange(diagonal_size)

    # 随机选择 k 个下标
    selected_indices = np.random.choice(diagonal_indices, k, replace=False)

    # 将选定的位置的元素设为指定的值
    matrix[selected_indices, selected_indices] = value


def find_ones_indices(matrix):
    ones_indices = []

    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            if matrix[i][j] == 1:
                ones_indices.append((i, j))

    return ones_indices



def find_union(A, B):
    # 使用set将列表转换为集合，去除重复元素
    set_A = set(A)
    set_B = set(B)

    # 使用union方法求并集
    union_result = set_A.union(set_B)

    # 将结果转换回列表形式
    result_list = list(union_result)

    return result_list


test = GameView()
test.first_view()
